package com.ryl.yomall.mq.listener;

import com.rabbitmq.client.Channel;
import com.ryl.yomall.mq.config.DeadLetterMqConfig;
import com.ryl.yomall.mq.config.DelayMQConfig;
;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.annotation.RabbitListeners;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Calendar;

/**
 * @Date 15:06
 * @Author ryl
 */
@Component

public class ConsumerMessage {


    //监听基于死信的消息
   // @RabbitListener(queues = DeadLetterMqConfig.queue_dead_2)
    @RabbitListeners ( value = {
            @RabbitListener(queues ={DeadLetterMqConfig.queue_dead_2,DelayMQConfig.queue_delay_1} ),

    })
    public void receiverDeadLetterMessage(String msg,Channel channel,Message message){


        try {
            System.out.println ("接收到的延迟消息:"+msg );
            System.out.println ( "接收到消息的时间:"+Calendar.getInstance ().getTime () );
            channel.basicAck ( message.getMessageProperties ().getDeliveryTag (),
                    false );
        } catch (IOException e) {
            e.printStackTrace ( );
        }

    }
    //接收消息
    @RabbitListener(queues = "queue1")
    public void receiverMessage(String msg,Channel channel,Message message){

        System.out.println ("收到消息:"+msg );
        //手动应答
        //参数一 :消息标记
        //参数2:  是否将消息放入队列 true:放回 false:不放回
        try {
            //int i=1/0;
            channel.basicAck ( message.getMessageProperties ().getDeliveryTag (),
                    false );

        } catch (Exception e) {
           // e.printStackTrace ( );
            //重新发送
            if(message.getMessageProperties ().isRedelivered ()){
                System.out.println("拒绝接收");
                try {
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),
                            false);
                } catch (IOException ex) {
                    ex.printStackTrace ( );
                }
            }else{
                //第一次发
                try {
                    System.out.println("第一次发：可以再发一次");
                    // 参数二：是否批量， 参数三：为是否重新回到队列，true重新入队
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),
                            false,true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
